﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WhsFacebook.Net.Web.Facebook.Handlers
{
    /// <summary>
    /// base class for image handlers receiving an instance id as parameter
    /// </summary>
    public abstract class ImageHttpHandler : SafeHttpHandler
    {
        protected sealed override void ProcessRequestSafe(HttpContext context)
        {
            // parse data
            var idStr = context.Request.Params["id"];

            if (string.IsNullOrEmpty(idStr))
                throw new ArgumentException("instance id not specified: missing 'id' query parameter", "id");

            Guid id;

            if (!Guid.TryParse(idStr, out id))
                throw new ArgumentException("instance id invalid: failed to parse 'id' query parameter", "id");

            if (id == Guid.Empty)
                throw new ArgumentException("instance id invalid: GUID in 'id' query parameter is Guid.Empty", "id");

            // output image
            context.Response.BufferOutput = true;

            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(GetImage(id));
        }

        protected abstract byte[] GetImage(Guid instanceId);
    }
}